/**
 * @Auther: ayo
 * @Date: 2018/8/22 17:01
 * @Description: // 使用localStorage来存储用户的登录状态，若浏览器不支持，则使用cookies
 */
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';
import { Utils } from './utils';

/**
 * 用枚举管理key值，防止字符串拼错
 */
export enum CacheKeys {
    TOKEN, AUTO_LOGIN, USER_INFO, JUMP_ADDRESS, LOGIN_DATA, AVATAR_URL, PAYMENT_INFO
}

@Injectable()
export class CacheProvider {

    constructor(public storage: Storage) {
        if (!storage) {
            throw new Error('Current browser does not support Local Storage');
        }
    }

    get(key: CacheKeys): Promise<any> {
        // return this.storage.get(CacheKeys[key]);
        try {
            return Promise.resolve().then(data => {
                if (Utils.isObject(JSON.parse(sessionStorage.getItem(CacheKeys[key])))) return JSON.parse(
                    sessionStorage.getItem(CacheKeys[key])); else return sessionStorage.getItem(CacheKeys[key]);
            });
        } catch (e) {}
    }


    set(key: CacheKeys, value: any): Promise<any> {
        // return this.storage.set(CacheKeys[key], value);
        return Promise.resolve().then(data => {
            if (Utils.isObject(value)) return sessionStorage.setItem(CacheKeys[key],
                JSON.stringify(value)); else return sessionStorage.setItem(CacheKeys[key], value);

        });
    }

    clear(): Promise<any> {
        // return this.storage.clear();
        return Promise.resolve().then(data => {
            sessionStorage.clear();
        });
    }

    remove(key: CacheKeys): Promise<any> {
        // return this.storage.remove(CacheKeys[key]);
        return Promise.resolve().then(data => {
            sessionStorage.removeItem(CacheKeys[key]);
        });
    }
}
